/*
 * @Description: 批量导入模板配置
 * @Author: Rfan
 * @Date: 2022-05-04 11:41:56
 * @LastEditTime: 2022-09-08 14:26:35
 */

import { useEffect, useRef, useState } from 'react';
import { Button, Form, Modal, Tabs } from 'antd';
import { fetchLevelByATId } from '@/api/archivesType';
import { fetchMetadata } from '@/api/metadata';
import { delItemById } from '@/utils/list';
import { useBatchManageContext } from '../../../contexts/BatchManageContext';
import { QUERY_METADATA_ALL } from '@/view/system/Metadata/constants';
import ExcelPane from './components/ExcelPane';
import ExcelLevel from './components/ExcelLevel';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';

const { TabPane } = Tabs;

interface UploadTemplateDialogProps extends ICommonDialog {
  data?: any; // 模板数据
}

/**
 * @description: 模板配置弹窗
 * @param {UploadTemplateDialogProps} props 弹窗传入参数
 * @return {ReactDOM} 模板配置弹窗tsx
 */
const UploadTemplateDialog: FC<UploadTemplateDialogProps> = (props) => {
  console.log('UploadTemplateDialog', props.data);
  const { visible, data, onClose } = props;
  const { activeBatch } = useBatchManageContext();
  // excel映射面板表单
  const [baseForm] = Form.useForm();
  const levelRef = useRef<any>();
  // 模板数据
  const [template, setTemplate] = useState<any>({});
  // 层级列表（不含组件级）
  const [levelList, setLevelList] = useState([]);
  // 所有层级的元数据
  const [levelMetadata, setLevelMetadata] = useState<any>({});
  // 当前选中的tab
  const [currentTab, setCurrentTab] = useState('1');

  useEffect(() => {
    if (visible) {
      const { archiveType } = activeBatch;
      fetchLevelByATId(activeBatch.archiveTypeId).then((res) => {
        const _list = delItemById(0, res.data, 'level');
        setLevelList(_list);
        _list.forEach((item: any) => {
          const { level } = item;
          const fieldQuery = {
            metadataFieldType: QUERY_METADATA_ALL,
            coordinate: {
              atType: archiveType.atType,
              atCode: archiveType.atCode,
              level
            }
          };
          !levelMetadata[level] &&
            fetchMetadata(fieldQuery).then((res: any) => {
              setLevelMetadata((state: any) => ({
                ...state,
                [level]: res.data
              }));
            });
        });
      });
    }
  }, [visible]);

  useEffect(() => {
    if (data) {
      setTemplate(data);
    }
  }, [data]);

  const onCancel = () => {
    onClose();
  };

  const tabsChange = (key: string) => {
    setCurrentTab(key);
  };

  const saveTemplate = () => {
    if (parseInt(currentTab, 10) === 1) {
      saveExecl();
    } else {
      saveRelation();
    }
  };

  const saveExecl = () => {
    baseForm.submit();
  };

  const saveRelation = () => {
    levelRef.current.submit();
  };

  return (
    <Modal
      title="条目Excel模板设计"
      visible={visible}
      className="upload-template"
      width={650}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <Button
          key="save"
          onClick={() => {
            saveTemplate();
          }}
        >
          {parseInt(currentTab, 10) === 1 ? '下一步' : '保存'}
        </Button>
      ]}
    >
      <Tabs activeKey={currentTab} onChange={tabsChange}>
        <TabPane tab="EXCEl表创建" key={1}>
          <ExcelPane
            levelList={levelList}
            levelMetadata={levelMetadata}
            form={baseForm}
            tplData={data}
            setIndexTab={setCurrentTab}
            updateTemplate={setTemplate}
          />
        </TabPane>
        <TabPane tab="EXECEL层级间匹配关系" key={2}>
          <ExcelLevel
            ref={levelRef}
            levelList={levelList}
            levelMetadata={levelMetadata}
            tplData={template}
            templateId={template.id}
            closeDialog={onCancel}
          />
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default UploadTemplateDialog;
